/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.upload.service.processor;

import cn.hutool.core.io.FileUtil;
import info.peigen.hotpot.common.service.base.processor.Processor;
import info.peigen.hotpot.common.service.base.processor.ProcessorServiceContext;
import info.peigen.hotpot.component.upload.domain.Upload;
import info.peigen.hotpot.component.upload.service.order.UploadOrder;
import info.peigen.hotpot.component.upload.service.result.UploadResult;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.UploadedFile;

import java.io.File;
import java.io.IOException;
import java.util.Optional;

/**
 * <b>(UploadTransferFileProcessor)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/11/14
 */
@SuppressWarnings({"rawtypes", "CallToPrintStackTrace"})
@Slf4j
@Component
public class UploadTransferFileProcessor extends AbstractUploadServiceProcessor implements Processor {
    @Override
    public Integer level() {
        return 20;
    }

    @Override
    public void execute(ProcessorServiceContext serviceContext) {
        UploadOrder  order        = (UploadOrder) serviceContext.getOrder();
        Upload       upload       = (Upload) serviceContext.getDomain();
        UploadResult result       = (UploadResult) serviceContext.getResult();
        UploadedFile uploadedFile = upload.getUploadedFile();
        String       fileName     = upload.getFileName();
        fileName = Optional.ofNullable(fileName).orElse(uploadedFile.getName());
        String dirPath = uploadProperties.getUploadPath() + Optional.ofNullable(order.getModulePath()).orElse("");
        File   dir     = new File(dirPath);
        FileUtil.mkdir(dir);
        String filePath = dirPath + fileName;
        File   file     = new File(filePath);
        try {
            uploadedFile.transferTo(file);
        } catch (IOException e) {
            result.setFail("上传文件异常,文件路径:filePath=" + filePath);
            e.printStackTrace();
            return;
        }
        result.setSuccess();
        result.setFilePath(filePath);
    }

}